<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-header class="header-container">
          <div class="logo">
            <img src="../img/yz.webp" alt="永泽游戏网" />
            <span class="yz">欢迎使用永泽游戏网</span>
          </div>
          <div class="header-right">
            <el-button type="danger" @click="logout">退出登录</el-button>
          </div>
        </el-header>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-scrollbar>
            <el-menu>
              <el-sub-menu index="1">
                <template #title>
                  <el-icon><message /></el-icon>
                </template>
                <el-menu-item-group>
                  <el-menu-item index="1-1">
                    <router-link to="/profile">修改个人信息</router-link>
                  </el-menu-item>
                  <el-menu-item index="1-2">
                    <router-link to="/upload">上传游戏</router-link>
                  </el-menu-item>
                  <el-menu-item index="1-3">
                    <router-link to="/gamelist">返回主页</router-link>
                  </el-menu-item>
                </el-menu-item-group>
              </el-sub-menu>
            </el-menu>
          </el-scrollbar>
        </el-aside>
        <el-main>
          <div class="profile-container">
            <el-descriptions
              title="个人资料"
              direction="vertical"
              border
              style="margin-top: 20px"
              v-if="userInfo"
            >
              <el-descriptions-item :rowspan="2" :width="140" label="头像" align="center">
                <el-image style="width: 100px; height: 100px" :src="userInfo.imgUrl" />
              </el-descriptions-item>
              <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
              <el-descriptions-item label="电话">{{ userInfo.phone }}</el-descriptions-item>
              <el-descriptions-item label="名字">{{ userInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="性别">
                <el-tag size="small">{{ userInfo.sex }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="身份证号">
                {{ userInfo.idNumber }}
              </el-descriptions-item>
            </el-descriptions>
            <el-button @click="dialogVisible = true" type="primary">修改个人信息</el-button>
            <el-button @click="centerDialog = true" type="danger">修改密码</el-button>
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :on-error="handleError"
              :http-request="customUpload"
            >
              <el-button type="primary" icon="el-icon-upload">上传头像</el-button>
            </el-upload>
          </div>
          <el-dialog v-model="centerDialog" title="修改密码" width="500" center>
            <el-form :model="form" ref="formRef" label-width="120px" class="change-password-form">
              <el-form-item label="原密码" :rules="[{ required: true, message: '请输入原密码', trigger: 'blur' }]">
                <el-input type="password" v-model="form.oldPassword" placeholder="请输入原密码" />
              </el-form-item>
              <el-form-item label="新密码" :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }]">
                <el-input type="password" v-model="form.newPassword" placeholder="请输入新密码" />
              </el-form-item>
              <el-form-item label="确认密码" :rules="[{ required: true, message: '请确认新密码', trigger: 'blur' }]">
                <el-input type="password" v-model="form.confirmPassword" placeholder="请再次输入新密码" />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="centerDialog = false">取消</el-button>
                <el-button type="primary" @click="changePassword">提交</el-button>
              </div>
            </template>
          </el-dialog>
          <el-dialog title="修改个人信息" v-model="dialogVisible" width="500px" center>
            <el-form :model="formData" ref="form" label-width="100px">
              <el-form-item label="用户名" prop="username" :rules="rules.username">
                <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
              </el-form-item>
              <el-form-item label="电话" prop="phone" :rules="rules.phone">
                <el-input v-model="formData.phone" placeholder="请输入电话号码"></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="formData.sex">
                  <el-radio label="男">男</el-radio>
                  <el-radio label="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="身份证号" prop="idNumber" :rules="rules.idNumber">
                <el-input v-model="formData.idNumber" placeholder="请输入身份证号"></el-input>
              </el-form-item>
              <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
              </div>
            </el-form>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import request from '../axios/request';
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '../stores/userStore';

const store = useAuthStore();
const router = useRouter();
const route = useRoute();
const userInfo = ref(null);
const centerDialog = ref(false);
const dialogVisible = ref(false);

// 页面键
const pageKey = computed(() => {
  const storedPageKey = sessionStorage.getItem('pageKey');
  return storedPageKey || `${route.path || '/profile'}-${Math.random().toString(36).substr(2, 9)}`;
});
// 当前用户
const currentUser = computed(() => store.getActiveUser(pageKey.value));

// 用户信息表单数据
const formData = ref({
  username: '',
  phone: '',
  sex: '男',
  idNumber: '',
});

// 修改密码表单数据
const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符之间', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '电话不能为空', trigger: 'blur' },
    { pattern: /^[0-9]{11}$/, message: '请输入有效的手机号', trigger: 'blur' },
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  idNumber: [
    { required: true, message: '身份证号不能为空', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}[1-9]\d{3}(\d{4}|\d{3}X)$/, message: '请输入有效的身份证号', trigger: 'blur' },
  ],
};

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请上传图片文件');
  }
  return isImage;
};

// 上传成功回调
const handleSuccess = async (response) => {
  if (response.code === 200) {
    const user = store.getActiveUser(pageKey.value);
    if (!user || !user.id) {
      ElMessage.error('未登录，无法更新头像');
      return;
    }
    try {
      const res = await request({
        url: '/user/insertImg',
        method: 'post',
        data: {
          id: user.id,
          imgUrl: response.data,
        },
        pageKey: pageKey.value,
      });
      if (res.data.code === 200) {
        await getUserInfo();
        ElMessage.success('头像更新成功');
      } else {
        ElMessage.error('头像更新失败');
      }
    } catch (err) {
      console.error('请求失败:', err.response?.data || err);
      ElMessage.error('请求失败，请检查网络');
    }
  } else {
    ElMessage.error('头像上传失败');
  }
};

// 上传失败回调
const handleError = (error) => {
  ElMessage.error('上传失败，请检查网络');
};

// 自定义上传请求
const customUpload = async (options) => {
  const file = options.file;
  const token = store.getToken(pageKey.value);

  if (!token) {
    ElMessage.error('未登录，无法上传');
    options.onError(new Error('未登录'));
    return;
  }

  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await request({
      url: '/games/common/upload',
      method: 'post',
      data: formData,
      pageKey: pageKey.value,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    if (response.data.code === 200) {
      options.onSuccess(response.data);
    } else {
      options.onError(new Error(response.data.msg || '上传失败'));
    }
  } catch (err) {
    console.error('上传失败:', err.response?.data || err);
    options.onError(err);
    ElMessage.error('上传失败，请检查网络');
  }
};

// 获取用户信息
const getUserInfo = async () => {
  const user = store.getActiveUser(pageKey.value);
  if (!user || !user.id) {
    ElMessage.error('未登录或用户ID无效');
    router.push('/login');
    return;
  }
  try {
    const res = await request({
      url: `/user/list?id=${user.id}`,
      method: 'get',
      pageKey: pageKey.value,
    });
    if (res.data.code === 200) {
      userInfo.value = res.data.data;
      // 初始化表单数据
      formData.value = {
        username: userInfo.value.username || '',
        phone: userInfo.value.phone || '',
        sex: userInfo.value.sex || '男',
        idNumber: userInfo.value.idNumber || '',
      };
    } else {
      ElMessage.error('获取用户信息失败');
    }
  } catch (err) {
    console.error('请求失败:', err.response?.data || err);
    ElMessage.error('请求用户信息失败');
    if (err.message === '登录已失效，请重新登录') {
      router.push('/login');
    }
  }
};

// 提交修改个人信息
const handleSubmit = async () => {
  const user = store.getActiveUser(pageKey.value);
  if (!user || !user.id) {
    ElMessage.error('未登录或用户ID无效');
    router.push('/login');
    return;
  }
  try {
    const res = await request({
      url: '/user/saveOrMod',
      method: 'post',
      data: {
        id: user.id,
        username: formData.value.username,
        phone: formData.value.phone,
        sex: formData.value.sex,
        idNumber: formData.value.idNumber,
      },
      pageKey: pageKey.value,
    });
    if (res.data.code === 200) {
      await getUserInfo();
      dialogVisible.value = false;
      ElMessage.success('个人信息修改成功');
    } else {
      ElMessage.error('修改失败');
    }
  } catch (err) {
    console.error('请求失败:', err.response?.data || err);
    ElMessage.error('请求失败，请检查网络');
  }
};

// 修改密码
const changePassword = async () => {
  const user = store.getActiveUser(pageKey.value);
  if (!user || !user.id) {
    ElMessage.error('未登录或用户ID无效');
    router.push('/login');
    return;
  }
  if (form.value.newPassword !== form.value.confirmPassword) {
    ElMessage.error('新密码和确认密码不一致');
    return;
  }
  try {
    const res = await request({
      url: '/user/changePassword',
      method: 'post',
      data: {
        userName: user.username,
        oldPassword: form.value.oldPassword,
        newPassword: form.value.newPassword,
      },
      pageKey: pageKey.value,
    });
    if (res.data.code === 200) {
      centerDialog.value = false;
      ElMessage.success('密码修改成功');
    } else {
      ElMessage.error('密码修改失败');
    }
  } catch (err) {
    console.error('请求失败:', err.response?.data || err);
    ElMessage.error('请求失败，请检查网络');
  }
};

// 退出登录
const logout = () => {
  // 清除本地存储中的 token 或用户信息
  request({
    url: '/login/logout',
    method: 'get',
    pageKey: pageKey.value,
  })
    .then((res) => {
      if (res.data.code === 200) {
              // 提示用户退出成功
        ElMessage({
          message: '退出登录成功',
          type: 'success',
        });
        store.logout(pageKey.value);
        // 跳转到登录页面
        router.push('/');
      } else {
        ElMessage.error('退出登录失败');
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage.error('请求失败，请检查网络');
    });

};

onMounted(async () => {
  store.initialize();
  const storedPageKey = sessionStorage.getItem('pageKey');
  if (storedPageKey) {
    await getUserInfo();
  } else {
    router.push('/login'); // 未登录跳转登录页
  }
});
</script>

<style scoped>
.common-layout {
  background: linear-gradient(135deg, #f4f6f9, #e0e7ff);
  min-height: 100vh;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.el-container {
  flex: 1;
  border-radius: 0;
  overflow: hidden;
  background: #ffffff;
}

/* Header Styling */
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: linear-gradient(90deg, #2c3e50, #34495e);
  color: #fff;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 1000;
  height: 60px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo img {
  height: 45px;
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.yz {
  font-size: 1.4rem;
  font-weight: bold;
  color: #ffffff;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.el-button {
  font-size: 14px;
  padding: 10px 20px;
  border-radius: 8px;
  transition: background-color 0.3s ease, transform 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* Aside Styling */
.el-aside {
  width: 200px;
  background-color: #ffffff;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 60px;
  bottom: 0;
  left: 0;
  z-index: 999;
  transition: width 0.3s ease;
}

.el-menu {
  border-right: none;
  height: 100%;
}

.el-sub-menu .el-icon {
  font-size: 18px;
  color: #409eff;
}

.el-menu-item {
  font-size: 14px;
  padding: 0 20px;
}

.el-menu-item a {
  color: #2c3e50;
  text-decoration: none;
  display: block;
  width: 100%;
}

.el-menu-item:hover {
  background-color: #f0f4f8;
}

/* Main Styling */
.el-main {
  margin-left: 200px;
  padding: 80px 20px 20px;
  min-height: calc(100vh - 60px);
  background: #f4f6f9;
}

.profile-container {
  max-width: 800px;
  margin: auto;
  padding: 25px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.1);
}

.el-descriptions {
  margin-top: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  background: #f9f9f9;
}

.el-descriptions-item {
  font-size: 16px;
  padding: 12px;
  border-bottom: 1px solid #e0e0e0;
}

.el-descriptions-item label {
  font-weight: bold;
  color: #2c3e50;
  font-size: 16px;
}

.el-descriptions-item:last-child {
  border-bottom: none;
}

.el-image {
  border-radius: 50%;
  border: 3px solid #e0e0e0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  width: 100px;
  height: 100px;
}

.el-tag {
  font-size: 14px;
  background: #409eff;
  color: white;
  border-radius: 5px;
}

.el-button.primary {
  margin: 15px 0;
  background: linear-gradient(90deg, #3498db, #2980b9);
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, background 0.3s ease;
}

.el-button.primary:hover {
  background: linear-gradient(90deg, #2980b9, #3498db);
  transform: scale(1.05);
}

.el-button[type="danger"] {
  background: linear-gradient(90deg, #e74c3c, #c0392b);
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, background 0.3s ease;
}

.el-button[type="danger"]:hover {
  background: linear-gradient(90deg, #c0392b, #e74c3c);
  transform: scale(1.05);
}

.avatar-uploader .el-button {
  background: linear-gradient(90deg, #2ecc71, #27ae60);
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease, background 0.3s ease;
}

.avatar-uploader .el-button:hover {
  background: linear-gradient(90deg, #27ae60, #2ecc71);
  transform: scale(1.05);
}

.profile-container .el-button + .el-button,
.profile-container .el-button + .avatar-uploader,
.profile-container .avatar-uploader + .el-button {
  margin-left: 15px;
}

/* Dialog Styling */
.el-dialog {
  border-radius: 10px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
  padding: 20px;
  width: 500px;
}

.el-dialog-title {
  font-size: 1.4rem;
  color: #333;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-input,
.el-radio-group {
  width: 100%;
  border-radius: 5px;
  padding: 8px;
  font-size: 14px;
}

.el-input::placeholder {
  color: #bdc3c7;
}

.el-radio-group .el-radio {
  margin-right: 20px;
  font-size: 14px;
}

.dialog-footer {
  text-align: center;
  padding: 15px;
}

.el-dialog .el-button {
  font-size: 14px;
  padding: 10px 20px;
}

/* Responsive Adjustments */
@media (max-width: 1024px) {
  .el-aside {
    width: 180px;
  }

  .el-main {
    margin-left: 180px;
    padding: 80px 15px 15px;
  }

  .profile-container {
    max-width: 100%;
    padding: 20px;
  }

  .el-descriptions-item {
    font-size: 14px;
    padding: 10px;
  }

  .el-descriptions-item label {
    font-size: 14px;
  }

  .el-image {
    width: 90px;
    height: 90px;
  }
}

@media (max-width: 768px) {
  .el-container {
    flex-direction: row;
  }

  .el-aside {
    width: 60px;
  }

  .el-main {
    margin-left: 60px;
    padding: 70px 10px 10px;
  }

  .el-menu-item a {
    font-size: 12px;
    text-align: center;
  }

  .profile-container {
    padding: 15px;
  }

  .el-descriptions-item {
    font-size: 15px;
    padding: 12px;
  }

  .el-button.primary,
  .el-button[type="danger"],
  .avatar-uploader .el-button {
    padding: 12px 20px;
    font-size: 15px;
  }

  .profile-container .el-button + .el-button,
  .profile-container .el-button + .avatar-uploader,
  .profile-container .avatar-uploader + .el-button {
    margin-left: 10px;
  }
}

@media (max-width: 480px) {
  .el-aside {
    width: 50px;
  }

  .el-main {
    margin-left: 50px;
    padding: 60px 8px 8px;
  }

  .el-menu-item a {
    font-size: 10px;
  }

  .profile-container {
    padding: 10px;
  }

  .el-descriptions-item {
    font-size: 14px;
    padding: 10px;
  }

  .el-button.primary,
  .el-button[type="danger"],
  .avatar-uploader .el-button {
    padding: 10px 15px;
    font-size: 14px;
  }
}
</style>